package cn.tedu.spotms.server.service.impl;

import cn.tedu.spotms.server.ex.ServiceException;
import cn.tedu.spotms.server.mapper.PermissionMapper;
import cn.tedu.spotms.server.pojo.dto.PermissionAddNewDTO;
import cn.tedu.spotms.server.pojo.entity.Permission;
import cn.tedu.spotms.server.pojo.vo.PermissionStandardVO;
import cn.tedu.spotms.server.service.IPermissionService;
import cn.tedu.spotms.server.web.State;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class PermissionServiceImpl implements IPermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public void addNew(PermissionAddNewDTO permissionAddNewDTO) {
        log.debug("开始添加权限:{}",permissionAddNewDTO);
        // 获取权限name
        String name = permissionAddNewDTO.getName();
        // 根据name查询数据库，判断结果是否不为null，若不为null，则抛出异常
        PermissionStandardVO resultByName = permissionMapper.getByName(name);
        if (resultByName != null) {
            log.debug("名称({})重复，即将抛出异常",name);
            throw new ServiceException(State.ERR_PERMISSION_NAME_DUPLICATE,"添加权限失败，权限名称("+name+")已存在!");
        }

        // 获取权限value
        String value = permissionAddNewDTO.getValue();
        // 根据value查询数据库，判断结果是否不为null，若不为null，则抛出异常
        PermissionStandardVO resultByValue = permissionMapper.getByValue(value);
        if (resultByValue != null) {
            log.debug("值({})重复，即将抛出异常",value);
            throw new ServiceException(State.ERR_PERMISSION_VALUE_DUPLICATE,"添加权限失败，权限值("+value+")已存在!");
        }

        // 创建Permission对象，将参数的属性复制到Permission对象中
        Permission permission = new Permission();
        BeanUtils.copyProperties(permissionAddNewDTO,permission);
        // 补全创建时间和更新时间两个属性值
        LocalDateTime now = LocalDateTime.now();
        permission.setGmtCreate(now);
        permission.setGmtModified(now);

        // 将数据插入到数据库，并判断返回行数
        int rows = permissionMapper.insert(permission);
        if (rows != 1) {
            log.debug("添加权限操作失败，即将抛出异常");
            throw new ServiceException(State.ERR_INSERT,"添加权限失败，服务器忙，请稍后再试!");
        }
        log.debug("添加权限完成!");
    }

    @Override
    public List<PermissionStandardVO> list() {
        return permissionMapper.list();
    }
}
